package com.youi.shop.commons.exceptions;

import com.youi.shop.commons.result.RespEntity;
import com.youi.shop.commons.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/11/9 15:03
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler{


    /**
     * 捕获全局异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespEntity<Object> handException(Exception ex) {
        log.error(ex.getCause().getMessage());
        return RespEntity.error();
    }


    /**
     * 校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RespEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();

        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();
            Object value = error.getRejectedValue();
            String msg = error.getDefaultMessage();
            String message = String.format("错误字段：%s，错误值：%s，原因：%s；", field, value, msg);
            stringBuilder.append(message).append("\r\n");
        }
        return RespEntity.error(StatusCode.PARAM_FAIL_CODE, stringBuilder.toString());
    }


    @ExceptionHandler(GlobalException.class)
    public RespEntity<Object> handGlobalException(GlobalException ex) {
        RespEntity<Object> error = RespEntity.error();
        error.setMessage(ex.errorMsg);
        error.setStatus(ex.errorCode);
        return error;
    }



}
